package com.googlecode.authproxy;

import java.util.Properties;
import java.io.*;

/**
 * @author Niels Bosma (niels.bosma@motorola.com)
 */
public class AuthProxySettings extends Properties
{
   private static final String PROPERITES_PATH = "webapps/authproxy/WEB-INF/authproxy.xml";

   private static AuthProxySettings instance = null;

   public static AuthProxySettings getInstance()
   {
      if(instance==null) instance = new AuthProxySettings();
      return instance;
   }

   private AuthProxySettings()
   {
      super(new Properties());

      this.defaults.setProperty("authproxy.proxySet", "false");
      this.defaults.setProperty("authproxy.proxyPort", "");
      this.defaults.setProperty("authproxy.proxyHost", "");
      this.defaults.setProperty("authproxy.proxyUser", "");
      this.defaults.setProperty("authproxy.proxyPassword", "");
      this.defaults.setProperty("authproxy.proxyAuthenticated", "false");

      try
      {
         this.loadFromXML(new FileInputStream(PROPERITES_PATH));
      } catch (Exception e) {}
   }

   public void parse(String settings)
   {
      try
      {
         this.loadFromXML(new ByteArrayInputStream(settings.getBytes()));
      } catch (Exception e) {}
   }

   public void save()
   {
      try
      {
         this.storeToXML(new FileOutputStream(PROPERITES_PATH), null);
      } catch (Exception e) {}
   }

   public void updateProxy()
   {
      Properties systemProps = System.getProperties();
      systemProps.put("http.proxySet", this.getProperty("authproxy.proxySet"));
      if(this.getProperty("authproxy.proxySet").equals("true"))
      {
         systemProps.put("http.proxyPort", this.getProperty("authproxy.proxyPort"));
         systemProps.put("http.proxyHost", this.getProperty("authproxy.proxyHost"));
         if(this.getProperty("authproxy.proxyAuthenticated").equals("true"))
         {
            systemProps.put("http.proxyUser", this.getProperty("authproxy.proxyUser"));
            systemProps.put("http.proxyPassword", this.getProperty("authproxy.proxyPassword"));
         }
         else
         {
            if(this.getProperty("http.proxyUser")!=null) this.remove("http.proxyUser");
            if(this.getProperty("http.proxyPassword")!=null) this.remove("http.proxyPassword");
         }
      }
      else
      {
         if(this.getProperty("http.proxyPort")!=null) this.remove("http.proxyPort");
         if(this.getProperty("http.proxyHost")!=null) this.remove("http.proxyHost");
         if(this.getProperty("http.proxyUser")!=null) this.remove("http.proxyUser");
         if(this.getProperty("http.proxyPassword")!=null) this.remove("http.proxyPassword");
      }
   }

}
